import {
  identifyBookByAI, uploadBookInfo
} from "@/api/api"

//示例:       url: "https://yuelu-annex.oss-cn-shenzhen.aliyuncs.com/a5b83886-2298-445f-95b5-a8928fe10b74.jpg"
Page({
  data: {
    uploading: false,
    isIdentifying: false,
    dialogVisible: false,
    progress: 0,
    fileList: [],
    imageList: [],
    bookInfo: {}
  },

  // 选择图片方法
  chooseImage: function () {
    if (this.data.fileList.length >= 2) {
      wx.showToast({
        title: '最多上传 2 张图片',
        icon: 'none'
      });
      return;
    }
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择'],
      success: (res) => {
        const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];
        wx.chooseMedia({
          count: 1, // 每次只选择一张图片
          mediaType: ['image'],
          sourceType,
          success: (res) => {
            const tempFiles = res.tempFiles;
            if (tempFiles.length > 0) {
              const file = tempFiles[0];
              const newFile = {
                path: file.tempFilePath,
              };
              this.uploadFile(newFile.path);
            }
          },
          fail: (err) => {
            console.error('选择图片失败', err);
          }
        });
      },
      fail: (err) => {
        console.error('显示操作菜单失败', err);
      }
    });
  },

  // 调用上传接口
  uploadFile: function (filePath) {
    this.setData({
      uploading: true,
      progress: 0
    });

    // 直接使用wx.uploadFile上传文件
    const uploadTask = wx.uploadFile({
      url: 'http://127.0.0.1:8080/other/fileUpload', // 服务器地址
      filePath: filePath,
      name: 'file', // 后端接收文件的字段名
      header: {
        'Authorization': getApp().Authorization || '', // 添加认证信息
      },
      success: (res) => {
        this.setData({
          progress: 100
        });

        // 解析返回的数据
        let result;
        try {
          result = JSON.parse(res.data);
        } catch (e) {
          console.error('解析返回数据失败', e);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          this.setData({
            uploading: false
          });
          return;
        }

        // 检查上传是否成功
        if (res.statusCode === 200 && result.code === 200) {
          const newFileList = this.data.fileList.concat({
            url: result.fileUrl || result.url || result.data
          });
          this.setData({
            fileList: newFileList,
            imageList: newFileList,
            uploading: false
          });
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          });

          if (newFileList.length < 2) {
            // 若还未达到 2 张，提示继续上传
            wx.showModal({
              title: '提示',
              content: '是否继续上传图片？',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  this.chooseImage();
                }
              }
            });
          }
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          this.setData({
            uploading: false
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.error('上传失败', err);
        this.setData({
          uploading: false
        });
      }
    });

    // 监听上传进度
    uploadTask.onProgressUpdate((res) => {
      this.setData({
        progress: res.progress
      });
    });
  },
  //开始识别
  async startRecognition() {
    if (this.data.isIdentifying) return;
    this.setData({
      isIdentifying: true
    })
    //image中的url拿出来构成一个数组
    const urls = this.data.imageList.map(item => item.url);
    console.log(urls);

    try {
      const res = await identifyBookByAI(urls);
      if (res.code === 200) {
        //如果返回的数据中一项数据都没有，就显示请重新上传，清空imageList和fileList
        if (!res.data.title && !res.data.author && !res.data.isbn && !res.data.publisher && res.data.publishYear === 0) {
          wx.showToast({
            title: '上传的图片不具有辨识度，请重新上传',
            icon: 'none',
            duration: 1000
          });
          this.setData({
            imageList: [],
            fileList: [],
            isIdentifying: false
          });
          return;
        } else {
          wx.showToast({
            title: '识别成功',
            icon: 'success',
            duration: 800
          });
          this.setData({
            isIdentifying: false,
            bookInfo: res.data,
          })
          console.log('识别结果:', this.data.bookInfo);
          setTimeout(() => {
            this.showDialog()
          }, 800)
          console.log('3123213', this.data.dialogVisible)
        }
      } else {
        this.setData({
          isIdentifying: false,
        })
        throw new Error
      }
    } catch (error) {
      wx.showToast({
        title: error.data?.message,
        icon: 'none'
      });
    } finally {
      this.setData({
        isIdentifying: false,
      })
    }
  },
  // 显示对话框
  showDialog() {
    this.setData({
      dialogVisible: true
    });
  },

  // 用户确认
  async onDialogConfirm(e) {
    const
      bookInfo = e.detail;
    console.log('用户确认:', e.detail);
    //调用uploadBookInfo接口
    try {
      const newBookInfo = {
        ...bookInfo,
        coverImage: this.data.imageList[0]?.url,
        backImage: this.data.imageList[1]?.url || '',
        otherImage:"[]",
        categoryId: bookInfo.categoryId,
        ownerId: getApp().userInfo.id,
        status: 0
      }
      console.log(newBookInfo)
      const res = await uploadBookInfo(newBookInfo);
      if (res.code === 200) {
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
        this.setData({
					bookInfo: {},
          dialogVisible: false
        });
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.showToast({
        title: error.data?.message,
        icon: 'none'
      });
    } finally {
      this.setData({
        bookInfo: {},
				imageList: [],
				fileList: [],
        dialogVisible: false
      });
    }

  },

  // 用户取消
  onDialogCancel() {
    console.log('用户取消');
    this.setData({
      dialogVisible: false
    });
  },

  // 数据变化
  onDialogChange(e) {
    const {
      bookInfo
    } = e.detail;
    this.setData({
      bookInfo
    });
  },
  //删除图片
  // 删除图片方法
  deleteImage (e) {
    const index = e.currentTarget.dataset.index;
    const imageList = this.data.imageList;
    imageList.splice(index, 1);
    this.setData({
      imageList: imageList,
      fileList: imageList
    });
		console.log(this.data.imageList)
  }
});